package com.wskj.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ijpay.core.kit.HttpKit;
import com.ijpay.core.kit.WxPayKit;
import com.wskj.common.annotation.DataScope;
import com.wskj.common.config.WxPayV3Bean;
import com.wskj.common.constant.RedisConstants;
import com.wskj.common.constant.UserConstants;
import com.wskj.common.core.domain.entity.SysRole;
import com.wskj.common.core.domain.entity.SysUser;
import com.wskj.common.core.domain.entity.TbUserTiktok;
import com.wskj.common.core.domain.model.LoginUser;
import com.wskj.common.core.mybatisplus.core.ServicePlusImpl;
import com.wskj.common.core.page.TableDataInfo;
import com.wskj.common.core.redis.RedisCache;
import com.wskj.common.exception.CustomException;
import com.wskj.common.utils.common.AssertUtils;
import com.wskj.common.utils.common.PageUtils;
import com.wskj.common.utils.common.SecurityUtils;
import com.wskj.common.utils.tool.Query;
import com.wskj.system.domain.SysPost;
import com.wskj.system.domain.SysUserPost;
import com.wskj.system.domain.SysUserRole;
import com.wskj.system.mapper.*;
import com.wskj.system.service.ISysConfigService;
import com.wskj.system.service.ISysUserService;
import com.wskj.tencent.service.ITencentService;
import com.wskj.workbench.bo.app.AppSysUserQueryBo;
import com.wskj.workbench.bo.app.AppTbUserJoinOrderDetailAddBo;
import com.wskj.workbench.bo.app.AppUserPasswordEditBo;
import com.wskj.workbench.domain.TbUserJoinOrder;
import com.wskj.workbench.domain.TbUserJoinOrderDetail;
import com.wskj.workbench.domain.TbUserWalletDetail;
import com.wskj.workbench.enums.UserJoinOrderOrderStatusEnum;
import com.wskj.workbench.enums.UserTypeEnum;
import com.wskj.workbench.enums.UserWalletDetailDetailTypeEnum;
import com.wskj.workbench.service.ITbUserJoinOrderDetailService;
import com.wskj.workbench.service.ITbUserJoinOrderService;
import com.wskj.workbench.service.ITbUserTiktokService;
import com.wskj.workbench.service.ITbUserWalletDetailService;
import com.wskj.workbench.vo.app.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysUserServiceImpl extends ServicePlusImpl<SysUserMapper, SysUser> implements ISysUserService {

    private final SysRoleMapper roleMapper;
    private final SysPostMapper postMapper;
    private final SysUserRoleMapper userRoleMapper;
    private final SysUserPostMapper userPostMapper;
    private final ISysConfigService configService;

    private final RedisCache redisCache;

    private final WxPayV3Bean wxPayV3Bean;


    private final ITbUserTiktokService tbUserTiktokService;

    private final ITbUserWalletDetailService tbUserWalletDetailService;

    private final ITbUserJoinOrderService tbUserJoinOrderService;

    private final ITbUserJoinOrderDetailService userJoinOrderDetailService;


    private final ISysConfigService sysConfigService;

    @Override
    @DataScope(deptAlias = "d", userAlias = "u", isUser = true)
    public TableDataInfo<SysUser> selectPageUserList(SysUser user) {
        return PageUtils.buildDataInfo(baseMapper.selectPageUserList(PageUtils.buildPage(), user));
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u", isUser = true)
    public List<SysUser> selectUserList(SysUser user) {
        return baseMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u", isUser = true)
    public TableDataInfo<SysUser> selectAllocatedList(SysUser user) {
        return PageUtils.buildDataInfo(baseMapper.selectAllocatedList(PageUtils.buildPage(), user));
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u", isUser = true)
    public TableDataInfo<SysUser> selectUnallocatedList(SysUser user) {
        return PageUtils.buildDataInfo(baseMapper.selectUnallocatedList(PageUtils.buildPage(), user));
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return baseMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return baseMapper.selectById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuilder idsStr = new StringBuilder();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (Validator.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        StringBuilder idsStr = new StringBuilder();
        for (SysPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (Validator.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        int count = Math.toIntExact(count(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, userName).last("limit 1")));
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = Validator.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = getOne(new LambdaQueryWrapper<SysUser>()
                .select(SysUser::getUserId, SysUser::getPhoneNumber)
                .eq(SysUser::getPhoneNumber, user.getPhoneNumber()).last("limit 1"));
        if (Validator.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = Validator.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = getOne(new LambdaQueryWrapper<SysUser>()
                .select(SysUser::getUserId, SysUser::getEmail)
                .eq(SysUser::getEmail, user.getEmail()).last("limit 1"));
        if (Validator.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        /*if (Validator.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new CustomException("不允许操作超级管理员用户");
        }*/
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser user) {
        // 生成自己的邀请码
        while (true) {
            String yqcode = RandomUtil.randomNumbers(6);
            List<SysUser> list = list(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getInviteCode, yqcode));
            if (CollectionUtil.isEmpty(list)) {
                user.setInviteCode(yqcode);
                user.setRecommendCode(yqcode);
                break;
            }
        }
        user.setInviteFullCode("0");


        // 新增用户信息
        int rows = baseMapper.insert(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.delete(new LambdaQueryWrapper<SysUserPost>().eq(SysUserPost::getUserId, userId));
        // 新增用户与岗位管理
        insertUserPost(user);


        // 判断用户的邀请码是否存在 如果不存在则去生成
        SysUser sysUser = getById(userId);
        if (ObjectUtil.isEmpty(sysUser.getInviteCode())) {

            // 生成自己的邀请码
            while (true) {
                String yqcode = RandomUtil.randomNumbers(6);
                List<SysUser> list = list(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getInviteCode, yqcode));
                if (CollectionUtil.isEmpty(list)) {
                    user.setInviteCode(yqcode);
                    user.setRecommendCode(yqcode);
                    break;
                }
            }
            user.setInviteFullCode("0");

        }

        int result = baseMapper.updateById(user);
        return result;
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId));
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserStatus(SysUser user) {
        Long userId = user.getUserId();
        // 获取token
        String token = redisCache.getCacheObject(RedisConstants.LOGIN_USERID_KEY + userId);
        redisCache.deleteObject(RedisConstants.LOGIN_TOKEN_KEY + token);
        redisCache.deleteObject(RedisConstants.LOGIN_USERID_KEY + userId);
        return baseMapper.updateById(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return baseMapper.updateById(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return baseMapper.update(null,
                new LambdaUpdateWrapper<SysUser>()
                        .set(SysUser::getAvatar, avatar)
                        .eq(SysUser::getUserName, userName)) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return baseMapper.updateById(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return baseMapper.update(null,
                new LambdaUpdateWrapper<SysUser>()
                        .set(SysUser::getPassword, password)
                        .eq(SysUser::getUserName, userName));
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (Validator.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.insertAll(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (Validator.isNotNull(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostMapper.insertAll(list);
            }
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (Validator.isNotNull(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.insertAll(list);
            }
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
        // 删除用户与岗位表
        userPostMapper.delete(new LambdaQueryWrapper<SysUserPost>().eq(SysUserPost::getUserId, userId));
        return baseMapper.deleteById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
        }
        List<Long> ids = Arrays.asList(userIds);
        // 删除用户与角色关联
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, ids));
        // 删除用户与岗位表
        userPostMapper.delete(new LambdaQueryWrapper<SysUserPost>().in(SysUserPost::getUserId, ids));
        return baseMapper.deleteBatchIds(ids);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (Validator.isNull(userList) || userList.size() == 0) {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = baseMapper.selectUserByUserName(user.getUserName());
                if (Validator.isNull(u)) {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public int reduceBalanceByUserId(Long userId, BigDecimal balance) {
        return baseMapper.reduceBalanceByUserId(userId, balance);
    }

    @Override
    public int increaseBalanceByUserId(Long userId, BigDecimal balance) {
        return baseMapper.increaseBalanceByUserId(userId, balance);
    }

    @Override
    public TableDataInfo<SysUser> selectPageNotSysUserList(SysUser user) {


        if (ObjectUtil.isNotEmpty(user.getTikUid())) {
            List<Long> userIds = tbUserTiktokService.list(Wrappers.lambdaQuery(TbUserTiktok.class).eq(TbUserTiktok::getTikUid, user.getTikUid()))
                    .stream().map(TbUserTiktok::getUserId).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(userIds)) {
                user.setUserIds(userIds);
            } else {
                user.setUserIds(Arrays.asList(0l));
            }
        }
        // 如果不是超级管理员 需要查询本用户和所有下级用户
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            SysUser sysUser = selectUserById(SecurityUtils.getUserId());
            String inviteFullCode = sysUser.getInviteFullCode() + sysUser.getInviteCode();
            user.setInviteFullCode(inviteFullCode);
        }
        Page<SysUser> sysUserPage = baseMapper.selectPageNotSysUserList(PageUtils.buildPage(), user);
        extracted(sysUserPage);
        return PageUtils.buildDataInfo(sysUserPage);
    }

    private void extracted(Page<SysUser> sysUserPage) {
        List<SysUser> records = sysUserPage.getRecords();
        for (SysUser sysUser : records) {

            SysUser parentUser = getOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUserId, sysUser.getZhiUserId()));

            sysUser.setParentUser(parentUser);


            // 直播收入
            BigDecimal zhiboshouyi = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                    .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                    .eq(TbUserWalletDetail::getDelFlag, 0)
                    .eq(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.ZHIBO.getValue())
                    .isNull(TbUserWalletDetail::getRecommendType)

            ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);


            sysUser.setLivePrice(zhiboshouyi);

            // 短视频收入
            BigDecimal duoshipinshouyi = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                    .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                    .eq(TbUserWalletDetail::getDelFlag, 0)
                    .eq(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.DUANSHIPIN.getValue())
                    .isNull(TbUserWalletDetail::getRecommendType)

            ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);

            sysUser.setVideoPrice(duoshipinshouyi);


            // 查询直推人数
            long directRecommend = count(Wrappers.lambdaQuery(SysUser.class)
                    .eq(SysUser::getZhiUserId, sysUser.getUserId())
                    .eq(SysUser::getDeleted, 0));
            // 查询间接推荐人数
            long indirectRecommend = count(Wrappers.lambdaQuery(SysUser.class)
                    .likeRight(SysUser::getInviteFullCode, sysUser.getInviteFullCode() + sysUser.getInviteCode())
                    .eq(SysUser::getDeleted, 0)
                    .ne(SysUser::getZhiUserId, sysUser.getUserId()));
            sysUser.setDirectRecommend(directRecommend);
            sysUser.setIndirectRecommend(indirectRecommend);


            // 查询直推佣金

            // 查询提现金额
            BigDecimal withdrawalPrice = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class).eq(TbUserWalletDetail::getUserId,
                            sysUser.getUserId()).eq(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.TIXIAN.getValue()))
                    .stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);


            // 查询直推人数
            List<Long> childs = list(Wrappers.lambdaQuery(SysUser.class)
                    .eq(SysUser::getZhiUserId, sysUser.getUserId())
                    .eq(SysUser::getDeleted, 0)).stream().map(SysUser::getUserId).collect(Collectors.toList());

            // 直推佣金
            if (ObjectUtil.isNotEmpty(childs)) {
                BigDecimal directRecommendPrice = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                        .in(TbUserWalletDetail::getRecommendId, childs)
                        .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                        .eq(TbUserWalletDetail::getDelFlag, 0)
                        .ne(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.TIXIAN.getValue())

                ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                sysUser.setDirectRecommendPrice(directRecommendPrice);


                // 直接推荐直播佣金
                BigDecimal directRecommendZhiboPrice = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                        .in(TbUserWalletDetail::getRecommendId, childs)
                        .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                        .eq(TbUserWalletDetail::getDelFlag, 0)
                        .in(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.ZHIBO.getValue())

                ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);

                sysUser.setDirectRecommendZhiboPrice(directRecommendZhiboPrice);


                // 直接推荐短视频佣金
                BigDecimal directRecommendDuanshipinPrice = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                        .in(TbUserWalletDetail::getRecommendId, childs)
                        .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                        .eq(TbUserWalletDetail::getDelFlag, 0)
                        .in(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.DUANSHIPIN.getValue())

                ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);

                sysUser.setDirectRecommendDuanshipinPrice(directRecommendDuanshipinPrice);


                // 直接推荐主播佣金
                BigDecimal directRecommendZhuboPrice = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                        .in(TbUserWalletDetail::getRecommendId, childs)
                        .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                        .eq(TbUserWalletDetail::getDelFlag, 0)
                        .in(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.TUIGUANGZHUBO.getValue())

                ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                sysUser.setDirectRecommendZhuboPrice(directRecommendZhuboPrice);


                // 直接推荐团长佣金
                BigDecimal directRecommendTuanzhangPrice = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                        .in(TbUserWalletDetail::getRecommendId, childs)
                        .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                        .eq(TbUserWalletDetail::getDelFlag, 0)
                        .in(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.TUIGUANGTUANZHANG.getValue())

                ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                sysUser.setDirectRecommendTuanzhangPrice(directRecommendTuanzhangPrice);


                // 直接推荐分公司佣金
                BigDecimal directRecommendFengongsiPrice = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                        .in(TbUserWalletDetail::getRecommendId, childs)
                        .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                        .eq(TbUserWalletDetail::getDelFlag, 0)
                        .in(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.TUIGUANGFENGONGSI.getValue())

                ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                sysUser.setDirectRecommendFengongsiPrice(directRecommendFengongsiPrice);


            } else {
                sysUser.setDirectRecommendPrice(BigDecimal.ZERO);
                sysUser.setDirectRecommendZhiboPrice(BigDecimal.ZERO);
                sysUser.setDirectRecommendDuanshipinPrice(BigDecimal.ZERO);
                sysUser.setDirectRecommendZhuboPrice(BigDecimal.ZERO);
                sysUser.setDirectRecommendTuanzhangPrice(BigDecimal.ZERO);
                sysUser.setDirectRecommendFengongsiPrice(BigDecimal.ZERO);

            }


            // 间接推荐人数
            List<Long> collect = list(Wrappers.lambdaQuery(SysUser.class)
                    .likeRight(SysUser::getInviteFullCode, sysUser.getInviteFullCode() + sysUser.getInviteCode())
                    .eq(SysUser::getDeleted, 0)
                    .ne(SysUser::getZhiUserId, sysUser.getUserId())).stream().map(SysUser::getUserId).collect(Collectors.toList());

            if (ObjectUtil.isNotEmpty(collect)) {
                // 间接推荐金额
                BigDecimal jiantuijine = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                        .in(TbUserWalletDetail::getRecommendId, collect)
                        .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                        .eq(TbUserWalletDetail::getDelFlag, 0)
                        .ne(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.TIXIAN.getValue())

                ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                sysUser.setIndirectRecommendPrice(jiantuijine);


                // 间接推荐直播佣金
                BigDecimal indirectRecommendZhiboPrice = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                        .in(TbUserWalletDetail::getRecommendId, collect)
                        .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                        .eq(TbUserWalletDetail::getDelFlag, 0)
                        .in(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.ZHIBO.getValue())

                ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);

                sysUser.setIndirectRecommendZhiboPrice(indirectRecommendZhiboPrice);


                // 间接推荐短视频佣金
                BigDecimal indirectRecommendDuanshipinPrice = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                        .in(TbUserWalletDetail::getRecommendId, collect)
                        .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                        .eq(TbUserWalletDetail::getDelFlag, 0)
                        .in(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.DUANSHIPIN.getValue())

                ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);

                sysUser.setIndirectRecommendDuanshipinPrice(indirectRecommendDuanshipinPrice);


                // 间接推荐主播佣金
                BigDecimal directRecommendZhuboPrice = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                        .in(TbUserWalletDetail::getRecommendId, collect)
                        .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                        .eq(TbUserWalletDetail::getDelFlag, 0)
                        .in(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.TUIGUANGZHUBO.getValue())

                ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                sysUser.setIndirectRecommendZhuboPrice(directRecommendZhuboPrice);


                // 间接推荐团长佣金
                BigDecimal directRecommendTuanzhangPrice = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                        .in(TbUserWalletDetail::getRecommendId, collect)
                        .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                        .eq(TbUserWalletDetail::getDelFlag, 0)
                        .in(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.TUIGUANGTUANZHANG.getValue())

                ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                sysUser.setIndirectRecommendTuanzhangPrice(directRecommendTuanzhangPrice);


                // 间接推荐分公司佣金
                BigDecimal directRecommendFengongsiPrice = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                        .in(TbUserWalletDetail::getRecommendId, collect)
                        .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                        .eq(TbUserWalletDetail::getDelFlag, 0)
                        .in(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.TUIGUANGFENGONGSI.getValue())

                ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                sysUser.setIndirectRecommendFengongsiPrice(directRecommendFengongsiPrice);


            } else {
                sysUser.setIndirectRecommendPrice(BigDecimal.ZERO);
                sysUser.setIndirectRecommendZhiboPrice(BigDecimal.ZERO);
                sysUser.setIndirectRecommendDuanshipinPrice(BigDecimal.ZERO);
                sysUser.setIndirectRecommendZhuboPrice(BigDecimal.ZERO);
                sysUser.setIndirectRecommendTuanzhangPrice(BigDecimal.ZERO);
                sysUser.setIndirectRecommendFengongsiPrice(BigDecimal.ZERO);
            }


            // 提现金额
            sysUser.setWithdrawalPrice(withdrawalPrice);


            // 平台赠送的
            BigDecimal pingtaizengsong = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                    .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                    .eq(TbUserWalletDetail::getDelFlag, 0)
                    .in(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.PINGTAIZENGSONG.getValue())

            ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            sysUser.setPlatformGift(pingtaizengsong);
            // 股权赠送的
            BigDecimal guquanzengsong = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                    .eq(TbUserWalletDetail::getUserId, sysUser.getUserId())
                    .eq(TbUserWalletDetail::getDelFlag, 0)
                    .in(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.GUQUANZNEGSONG.getValue())

            ).stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            sysUser.setEquityGift(guquanzengsong);

            // 直推佣金+间推佣金+平台赠送+股权分红
            sysUser.setDirectAndIndirectRecommendPrice(sysUser.getDirectRecommendPrice().add(sysUser.getIndirectRecommendPrice()).add(pingtaizengsong).add(guquanzengsong));
            // 小程序上展示的值=直推佣金+间推佣金+平台赠送+股权分红-提现的钱
            sysUser.setDirectAndIndirectRecommendTixianPrice(sysUser.getDirectRecommendPrice().add(sysUser.getIndirectRecommendPrice())
                    .add(pingtaizengsong).add(guquanzengsong)
                    .subtract(withdrawalPrice));

        }
    }

    @Override
    public TableDataInfo<SysUser> childrenListPage(SysUser user) {
        // 如果是间推
        if (user.getRecommendType().equals("2")) {
            SysUser mouUer = selectUserById(user.getUserId());
            String inviteFullCode = mouUer.getInviteFullCode() + mouUer.getInviteCode();
            user.setInviteFullCode(inviteFullCode);
        }

        Page<SysUser> sysUserPage = baseMapper.selectPageNotSysUserList(PageUtils.buildPage(), user);
        extracted(sysUserPage);
        return PageUtils.buildDataInfo(sysUserPage);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     * @parma userType 用户类型
     */
    @Override
    public SysUser selectUserByUserNameAndUserType(String userName, String userType) {
        return baseMapper.selectUserByUserNameAndUserType(userName, userType);
    }

    @Override
    public void wxPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> map = new HashMap<>(12);

        String timestamp = request.getHeader("Wechatpay-Timestamp");
        String nonce = request.getHeader("Wechatpay-Nonce");
        String serialNo = request.getHeader("Wechatpay-Serial");
        String signature = request.getHeader("Wechatpay-Signature");

        log.info("timestamp:{} nonce:{} serialNo:{} signature:{}", timestamp, nonce, serialNo, signature);
        String result = HttpKit.readData(request);
        log.info("支付通知密文 {}", result);

        // 需要通过证书序列号查找对应的证书，verifyNotify 中有验证证书的序列号
        String plainText = WxPayKit.verifyNotify(serialNo, result, signature, nonce, timestamp,
                wxPayV3Bean.getApiKey3(), wxPayV3Bean.getPlatformCertPath());

        log.info("支付通知明文 {}", plainText);

        // 修改订单状态为已支付
        JSONObject jsonObject = JSONUtil.parseObj(plainText);
        String userId = jsonObject.getStr("out_trade_no");

        // TODO 操作业务

        if (StrUtil.isNotEmpty(plainText)) {
            response.setStatus(200);
            map.put("code", "SUCCESS");
            map.put("message", "SUCCESS");
        } else {
            response.setStatus(500);
            map.put("code", "ERROR");
            map.put("message", "签名错误");
        }
        response.setHeader("Content-type", ContentType.JSON.toString());
        response.getOutputStream().write(JSONUtil.toJsonStr(map).getBytes(StandardCharsets.UTF_8));
        response.flushBuffer();

    }

    @Override
    public boolean updatePassword(AppUserPasswordEditBo editVo) {
        SysUser sysUser = getById(SecurityUtils.getUserId());
        AssertUtils.isTrue(SecurityUtils.matchesPassword(editVo.getOldPassword(), sysUser.getPassword()), "旧密码输入不正确");
        sysUser.setPassword(SecurityUtils.encryptPassword(editVo.getNewPassword()));
        boolean result = updateById(sysUser);
        return result;
    }

    @Override
    public AppUserInfoVo getDetail() {
        AppUserInfoVo appUserInfoVo = getVoById(SecurityUtils.getUserId(), AppUserInfoVo.class);


        // 查询抖音号明细
        List<AppTbUserTiktokVo> appTbUserTiktokVos = tbUserTiktokService.listVo(Wrappers.lambdaQuery(TbUserTiktok.class)
                .eq(TbUserTiktok::getUserId, appUserInfoVo.getUserId()), AppTbUserTiktokVo.class);
        appUserInfoVo.setTiktokList(appTbUserTiktokVos);


        // 查询我的所有佣金(过滤掉提现的数据和导入的数据)
        BigDecimal totalAmount = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                        .eq(TbUserWalletDetail::getUserId,
                                SecurityUtils.getUserId()).ne(TbUserWalletDetail::getDetailType,
                                UserWalletDetailDetailTypeEnum.TIXIAN.getValue())
                        .isNotNull(TbUserWalletDetail::getRecommendType)
                )
                .stream().map(TbUserWalletDetail::getDetailPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 查询提现的金额
        BigDecimal withdrawalPrice = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class).eq(TbUserWalletDetail::getUserId,
                        SecurityUtils.getUserId()).eq(TbUserWalletDetail::getDetailType, UserWalletDetailDetailTypeEnum.TIXIAN.getValue()))
                .stream().map(TbUserWalletDetail::getDetailPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        // 目前余额
        BigDecimal muqian = totalAmount.subtract(withdrawalPrice);
        appUserInfoVo.setTotalAmount(muqian);


        // 查询钱包明细
        List<AppTbUserWalletDetailVo> detailList = tbUserWalletDetailService.listVo(Wrappers.lambdaQuery(TbUserWalletDetail.class)
                .eq(TbUserWalletDetail::getUserId, appUserInfoVo.getUserId()), AppTbUserWalletDetailVo.class);
        appUserInfoVo.setWalletList(detailList);


        // 查询昨日之前的收益
        BigDecimal yesterdeyAmount = tbUserWalletDetailService.getYesterdeyAmount();
        // 查询昨日的提现金额
        BigDecimal yesterdeyTixianAmount = tbUserWalletDetailService.getYesterdeyTixianAmount();
        // 查询昨日实际的钱
        BigDecimal zuori = yesterdeyAmount.subtract(yesterdeyTixianAmount);
        // 比昨日下降
        appUserInfoVo.setCompareAmount(muqian.subtract(zuori));


        // 查询最近最新一条的申请记录
        AppTbUserJoinOrderInfoVo joinOrderVo = tbUserJoinOrderService.getVoOne(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getUserId,
                SecurityUtils.getUserId()).orderByDesc(TbUserJoinOrder::getCreateTime).last("limit 1"), AppTbUserJoinOrderInfoVo.class);
        if (ObjectUtil.isNotEmpty(joinOrderVo)) {

            // 查询入住详情
            List<AppTbUserJoinOrderDetailVo> appTbUserJoinOrderDetailVos = userJoinOrderDetailService.
                    listVo(Wrappers.lambdaQuery(TbUserJoinOrderDetail.class).eq(TbUserJoinOrderDetail::getJoinOrderId, joinOrderVo.getId()),
                            AppTbUserJoinOrderDetailVo.class);

            joinOrderVo.setDetailList(appTbUserJoinOrderDetailVos);

        }
        appUserInfoVo.setJoinInfo(joinOrderVo);

        // 查询我的推广收益
        BigDecimal promoAmount = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class).eq(TbUserWalletDetail::getUserId,
                        SecurityUtils.getUserId()).in(TbUserWalletDetail::getDetailType,
                        UserWalletDetailDetailTypeEnum.TUIGUANGZHUBO.getValue(), UserWalletDetailDetailTypeEnum.TUIGUANGTUANZHANG.getValue(),
                        UserWalletDetailDetailTypeEnum.TUIGUANGFENGONGSI.getValue())).stream().map(TbUserWalletDetail::getDetailPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        appUserInfoVo.setPromoAmount(promoAmount.subtract(withdrawalPrice));


        // 查询我的抖音收益
        BigDecimal tiktokAmount = tbUserWalletDetailService.list(Wrappers.lambdaQuery(TbUserWalletDetail.class).eq(TbUserWalletDetail::getUserId,
                                SecurityUtils.getUserId()).in(TbUserWalletDetail::getDetailType,
                                UserWalletDetailDetailTypeEnum.ZHIBO.getValue(), UserWalletDetailDetailTypeEnum.DUANSHIPIN.getValue())
                        .isNull(TbUserWalletDetail::getRecommendType)
                )
                .stream().map(TbUserWalletDetail::getDetailPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        appUserInfoVo.setTiktokAmount(tiktokAmount.subtract(withdrawalPrice));


        return appUserInfoVo;
    }

    @Override
    public TableDataInfo<AppTeamVo> getPageTeam(Query query, AppSysUserQueryBo bo) {
        // 查询当前用户
        SysUser sysUser = getById(SecurityUtils.getUserId());
        String inviteFullCode = sysUser.getInviteFullCode() + sysUser.getInviteCode();
        Page<AppTeamVo> pageTeam = baseMapper.getPageTeam(PageUtils.buildPage(), bo, inviteFullCode, sysUser.getUserId());
        List<AppTeamVo> records = pageTeam.getRecords();
        // 一个用户有可能对应多个抖音号
        for (AppTeamVo record : records) {
            List<TbUserTiktok> list = tbUserTiktokService.list(Wrappers.lambdaQuery(TbUserTiktok.class).eq(TbUserTiktok::getUserId, record.getUserId()));
            List<String> collect = list.stream().map(TbUserTiktok::getTikUid).collect(Collectors.toList());
            record.setTikUidList(collect);
        }
        return PageUtils.buildDataInfo(pageTeam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancleAuth() {
        SysUser sysUser = getById(SecurityUtils.getUserId());
        AssertUtils.isTrue(sysUser.getAuthStatus().equals("3"), "只有认证中的状态才可以取消审核");
        sysUser.setAuthStatus("1");
        boolean result = updateById(sysUser);
        // 删除掉最近的申请记录
        List<TbUserJoinOrder> list = tbUserJoinOrderService.list(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getUserId,
                        SecurityUtils.getUserId()).eq(TbUserJoinOrder::getOrderStatus, UserJoinOrderOrderStatusEnum.YIZHIFU.getValue())
                .orderByDesc(TbUserJoinOrder::getCreateTime).last("limit 1"));
        for (TbUserJoinOrder tbUserJoinOrder : list) {

            List<TbUserJoinOrderDetail> list1 = userJoinOrderDetailService.list(Wrappers.lambdaQuery(TbUserJoinOrderDetail.class)
                    .eq(TbUserJoinOrderDetail::getJoinOrderId,
                            tbUserJoinOrder.getId()));
            if (ObjectUtil.isNotEmpty(list1)) {
                userJoinOrderDetailService.removeBatchByIds(list1);
            }
        }

        if (ObjectUtil.isNotEmpty(list)) {
            tbUserJoinOrderService.removeBatchByIds(list);
        }

        return result;
    }

    @Override
    public boolean notAuth() {
        SysUser sysUser = getById(SecurityUtils.getUserId());
        AssertUtils.isTrue(sysUser.getAuthStatus().equals("2"), "只有认证不通过的状态才可以不再审核");
        sysUser.setAuthStatus("4");
        boolean result = updateById(sysUser);
        return result;
    }


    @Override
    public AppZhaoshangVo getZhaoShang() {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = getById(userId);
        String userType = sysUser.getUserType();

        AppZhaoshangVo appZhaoshangVo = new AppZhaoshangVo();

        AssertUtils.isTrue(UserTypeEnum.TUANZHANG.getValue().equals(userType) || UserTypeEnum.FENGONGSI.getValue().equals(userType),
                "只有团长或者分公司才有招商名额");
        if (UserTypeEnum.TUANZHANG.getValue().equals(userType)) {
            BigDecimal identityAmount = new BigDecimal(configService.selectConfigByKey("zhubo_price"));
            // 查询直推的下级
            List<AppZhaoshangDetailVo> xiaji = listVo(Wrappers.lambdaQuery(SysUser.class)
                            .eq(SysUser::getZhiUserId, sysUser.getUserId())
                            .eq(SysUser::getDeleted, 0)
                    , AppZhaoshangDetailVo.class);


            // 主播名额要减去的数量
            int zhuminger = 0;
            // 直推的主播
            List<AppZhaoshangDetailVo> zhuboList = new ArrayList<>();
            for (AppZhaoshangDetailVo appZhaoshangDetailVo : xiaji) {
                // 如果是主播
                if (UserTypeEnum.ZHUBO.getValue().equals(appZhaoshangDetailVo.getUserType())) {
                    zhuboList.add(appZhaoshangDetailVo);
                } else if (UserTypeEnum.TUANZHANG.getValue().equals(appZhaoshangDetailVo.getUserType())) {
                    // 查询他曾经有没有主播身份 如果有的话 证明升级过身份
                    long count = tbUserJoinOrderService.count(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getUserType,
                            UserTypeEnum.ZHUBO.getValue()).eq(TbUserJoinOrder::getOrderStatus,
                            UserJoinOrderOrderStatusEnum.SHENHETONGGUO.getValue()).eq(TbUserJoinOrder::getUserId, appZhaoshangDetailVo.getUserId()));
                    if (count > 0) {
                        zhuminger = zhuminger + 1;
                    }
                } else if (UserTypeEnum.FENGONGSI.getValue().equals(appZhaoshangDetailVo.getUserType())) {
                    // 查询他曾经有没有主播身份 如果有的话 证明升级过身份
                    long count = tbUserJoinOrderService.count(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getUserType,
                            UserTypeEnum.ZHUBO.getValue()).eq(TbUserJoinOrder::getOrderStatus,
                            UserJoinOrderOrderStatusEnum.SHENHETONGGUO.getValue()).eq(TbUserJoinOrder::getUserId, appZhaoshangDetailVo.getUserId()));
                    if (count > 0) {
                        zhuminger = zhuminger + 1;
                    }
                }
            }

            for (AppZhaoshangDetailVo appZhaoshangDetailVo : zhuboList) {
                appZhaoshangDetailVo.setIdentityAmount(identityAmount);
            }
            appZhaoshangVo.setZhuboList(zhuboList);


            // 查询团长有几个主播招商名额
            String zbzs = sysConfigService.selectConfigByKey("tz_zs_me");
            appZhaoshangVo.setZhuboNum(String.valueOf(Long.valueOf(zbzs) - zhuminger));

            appZhaoshangVo.setSfZsZb("1");
            appZhaoshangVo.setSfZsTz("2");


        } else if (UserTypeEnum.FENGONGSI.getValue().equals(userType)) {

            // 查询所有的直属下级
            List<AppZhaoshangDetailVo> xiaji = listVo(Wrappers.lambdaQuery(SysUser.class)
                            .eq(SysUser::getZhiUserId, sysUser.getUserId())
                            .eq(SysUser::getDeleted, 0)
                    , AppZhaoshangDetailVo.class);

            // 主播名额要减去的数量
            int zhuminger = 0;
            // 团长名额要减去的数量
            int tuanminger = 0;
            // 直推的主播
            List<AppZhaoshangDetailVo> zhuboList = new ArrayList<>();
            // 直推的团长
            List<AppZhaoshangDetailVo> tuanzhangList = new ArrayList<>();
            for (AppZhaoshangDetailVo appZhaoshangDetailVo : xiaji) {
                // 如果是主播
                if (UserTypeEnum.ZHUBO.getValue().equals(appZhaoshangDetailVo.getUserType())) {

                    zhuboList.add(appZhaoshangDetailVo);


                } else if (UserTypeEnum.TUANZHANG.getValue().equals(appZhaoshangDetailVo.getUserType())) {

                    tuanzhangList.add(appZhaoshangDetailVo);

                    // 查询他曾经有没有主播身份 如果有的话 证明升级过身份
                    long count = tbUserJoinOrderService.count(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getUserType,
                            UserTypeEnum.ZHUBO.getValue()).eq(TbUserJoinOrder::getOrderStatus,
                            UserJoinOrderOrderStatusEnum.SHENHETONGGUO.getValue()).eq(TbUserJoinOrder::getUserId, appZhaoshangDetailVo.getUserId()));
                    if (count > 0) {
                        zhuminger = zhuminger + 1;
                    }

                } else if (UserTypeEnum.FENGONGSI.getValue().equals(appZhaoshangDetailVo.getUserType())) {

                    // 查询他曾经有没有主播身份 如果有的话 证明升级过身份
                    long count = tbUserJoinOrderService.count(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getUserType,
                            UserTypeEnum.ZHUBO.getValue()).eq(TbUserJoinOrder::getOrderStatus,
                            UserJoinOrderOrderStatusEnum.SHENHETONGGUO.getValue()).eq(TbUserJoinOrder::getUserId, appZhaoshangDetailVo.getUserId()));

                    if (count > 0) {
                        zhuminger = zhuminger + 1;
                    }

                    // 查询他曾经有没有团长身份 如果有的话 证明升级过身份
                    long tuancount = tbUserJoinOrderService.count(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getUserType,
                            UserTypeEnum.TUANZHANG.getValue()).eq(TbUserJoinOrder::getOrderStatus,
                            UserJoinOrderOrderStatusEnum.SHENHETONGGUO.getValue()).eq(TbUserJoinOrder::getUserId, appZhaoshangDetailVo.getUserId()));

                    if (tuancount > 0) {
                        tuanminger = tuanminger + 1;
                    }
                }
            }


            BigDecimal identityAmount = new BigDecimal(configService.selectConfigByKey("zhubo_price"));
            // 查询直推的主播
            for (AppZhaoshangDetailVo appZhaoshangDetailVo : zhuboList) {
                appZhaoshangDetailVo.setIdentityAmount(identityAmount);
            }
            appZhaoshangVo.setZhuboList(zhuboList);


            // 查询直推的团长
            BigDecimal tuanzhangAmount = new BigDecimal(configService.selectConfigByKey("tuanzhang_price"));
            for (AppZhaoshangDetailVo appZhaoshangDetailVo : tuanzhangList) {
                appZhaoshangDetailVo.setIdentityAmount(tuanzhangAmount);
            }
            appZhaoshangVo.setTuanzhangList(tuanzhangList);

            appZhaoshangVo.setSfZsZb("1");
            appZhaoshangVo.setSfZsTz("1");

            // 查询分公司有几个主播招商名额
            String zbzs = sysConfigService.selectConfigByKey("fgs_zb_zs_me");
            appZhaoshangVo.setZhuboNum(String.valueOf(Long.valueOf(zbzs) - zhuminger));
            // 查询分公司有几个团长招商名额
            String tuanzhangNum = sysConfigService.selectConfigByKey("fgs_tz_zs_me");
            appZhaoshangVo.setTuanzhangNum(String.valueOf(Long.valueOf(tuanzhangNum) - tuanminger));

        }
        return appZhaoshangVo;
    }

    @Override
    public AppTeamTotalVo teamTotal() {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = getById(userId);
        long count = count(Wrappers.lambdaQuery(SysUser.class)
                .likeRight(SysUser::getInviteFullCode, sysUser.getInviteFullCode() + sysUser.getInviteCode())
                .eq(SysUser::getDeleted, 0));
        AppTeamTotalVo appTeamTotalVo = new AppTeamTotalVo();
        appTeamTotalVo.setTotalNum(count);
        return appTeamTotalVo;
    }
}
